package phone.qyg.com.qyg.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.app.adapter.recycler.CommonAdapter;
import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.RecycleViewDivider;
import com.app.adapter.recycler.base.ViewHolder;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.app.view.BaseViewStateLayout;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;
import com.liaoinstan.springview.container.AliFooter;
import com.liaoinstan.springview.container.AliHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.Venues;
import phone.qyg.com.qyg.utils.PopuRecycle;

/**
 * 作者：lblbh on 2017/11/29 16:31
 * 邮箱：lanbuhan@163.com
 * 功能：文化场馆 列表
 */
@ContentView(R.layout.venues_list)
public class VenuesListActivity extends BaseActivity {

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.find)
    TextView find;

    @ViewInject(R.id.act_one)
    TextView act_one;

    @ViewInject(R.id.act_there)
    TextView act_there;

    @ViewInject(R.id.act_four)
    TextView act_four;

    @ViewInject(R.id.linear)
    LinearLayout linear;

    BaseViewStateLayout baseView;

    PopupWindow popupWindow;

    SpringView springview;

    RecyclerView recycler;

    List<Base> citys;//城市列表

    List<Base> status;//类别列表

    List<Base> sorts;//排序列表

    Base city;//城市

    Base statu;//类别

    Base sort;//排序

    List<Venues> models;

    CommonAdapter adapter;

    boolean isForce;

    int page_no,totalpage;


    @Override
    public void initData(Bundle savedInstanceState) {

        initType();

        baseView = new BaseViewStateLayout(QXApplication.getContext()) {

            @Override
            public View obtionView() {
                View sucessView = View.inflate(QXApplication.getContext(), R.layout.base_spring_recycler,null);
                recycler = (RecyclerView) sucessView.findViewById(R.id.recycler);
                springview = (SpringView) sucessView.findViewById(R.id.springview);

                springview.setListener(new SpringView.OnFreshListener() {
                    @Override
                    public void onRefresh() {
                        isForce = true;
                        getInitNetwork(false);
                    }

                    @Override
                    public void onLoadmore() {
                        if(isRequestList(models) && (page_no < totalpage) ){
                            getInitNetwork(true);
                        }else{
                            PromptManager.showToast(R.string.more_no_datas);
                            springview.onFinishFreshAndLoad();
                        }

                    }
                });

                springview.setHeader(new AliHeader(QXApplication.getContext(),false));
                springview.setFooter(new AliFooter(QXApplication.getContext(),false));
                return sucessView;
            }

            @Override
            public Object obtionData() {

                return DELFAUTSTATE;
            }
        };

        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linear.addView(baseView,layoutParams);
        x.view().inject(linear);

    }

    /**
     * 执行网络请求
     */
    private void getInitNetwork(final boolean isPull){


        if(isPull){
            page_no = page_no + 1;
        }else{
            page_no = 1;
        }

        if(isForce){
            page_no = 1;
        }

        /**
         *  Base city;//城市

         Base status;//类别

         Base sort;//排序


         “cityId”:59,   //当前所在城市ID”
         “venueType”:1      //场馆类型 0：文化馆  1：图书馆  2：博物馆  3：美术馆'
         “venueName”:”内蒙古体育馆”,   //检索场馆名称（非必填）
         “intellSort”:1             //智能排序 0:距离 1评价
         “pageNo” : 1 //  分页码
         */

        mapKeys.put(AppHttpKey.CITY_ID,themeItemId(city));
        mapKeys.put(AppHttpKey.VENUE_TYPE_ID,themeItemId(statu));
        mapKeys.put(AppHttpKey.INTELL_SORT,themeItemId(sort));
        mapKeys.put(AppHttpKey.PAGE_NO,String.valueOf(page_no));

        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.VENUE_PAGE_LIST,
                mapKeys,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);

                        List<Venues> temps = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.VENUE_LIST, Venues.class);

                        totalpage = JSONTool.requestJSONfindNameCount(result,JSONTool.Enum.DATA,JSONTool.Enum.TOTALPAGE);

                        if(!isRequestList(temps) && !isPull){
                            baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_EMPTY);
                            baseView.stateView();
                            return;
                        }
                        //成功获取到数据
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_SUCESS);
                        baseView.stateView();

                        setModelData(isPull,temps);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_ERROE);
                        baseView.stateView();
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                        springview.onFinishFreshAndLoad();
                    }
                });
    }


    private void setModelData(final boolean isPull, List<Venues> temps) {
        if ((adapter == null && isRequestList(temps)) || isForce) {
            isForce = false;

            //数据初始化工作
            models = temps;

            adapter = new CommonAdapter<Venues>(QXApplication.getContext(),R.layout.item_venue,models) {
                @Override
                protected void convert(ViewHolder holder, Venues model, int position) {
                    holder.setText(R.id.item_title,model.title);
                    holder.setText(R.id.item_distance,String.valueOf(model.distance));
                    holder.setText(R.id.item_map,model.address);
                    holder.setImage(R.id.item_img,model.fixImgUrl, OptionImageUtils.getRectRatio43());
                    holder.setStar(R.id.rating_bar,model.star);
                }
            };

            adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    SystemPrintl.systemPrintl("我在点击场馆--->>>"+position);
                    Object obj = adapter.getDatas().get(position);
                    TransformController.transformControllerModel(QXApplication.getContext(), VenuesDetailActivity.class,obj);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });

            recycler.setAdapter(adapter);
        }

        if (isPull && isRequestList(models) && isRequestList(temps)) {
            //上拉加载数据
            models.addAll(temps);
        }
        //刷新数据
        if (adapter != null)
            adapter.notifyDataSetChanged();
    }


    private void initType(){
        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.VENUE_SELECT_CONDITION,
                mapKeys,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        citys = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.AREA_LIST,Base.class);
                        status = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.VENUE_TYPE_LIST,Base.class);
                        sorts = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.SORT_LIST,Base.class);

                        if(isRequestList(citys))
                            city = citys.get(0);

                        if(isRequestList(status))
                            statu = status.get(0);

                        if(isRequestList(sorts))
                            sort = sorts.get(0);
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                        getInitNetwork(false);
                    }
                });
    }


    @Event(value = {R.id.back,R.id.find,R.id.act_one,R.id.act_there,R.id.act_four})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.find:
                TransformController.transformControllerModel(QXApplication.getContext(),
                        AppFindActivity.class,
                        new Base(QXApplication.getContext().getString(R.string.venue)));
                break;
            case R.id.act_one:
                if(!isRequestList(citys)){
                    PromptManager.showToast(R.string.city_county_hint);
                    return;
                }
                if(popupWindow!=null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                    return;
                }
                popupWindow = PopuRecycle.setPopuThemes(this,v, citys,city, new PopuRecycle.OnClickState() {
                    @Override
                    public void OnItemClick(Object model, PopuRecycle.EnumType enumType) {
                        Base base = (Base) model;
                        if(city != base) {
                            city = base;
                            act_one.setText(city.title);
                            isForce = true;
                            getInitNetwork(false);
                        }
                    }
                });
                break;
            case R.id.act_there:
                if(!isRequestList(status)){
                    PromptManager.showToast(R.string.city_venue_hint);
                    return;
                }
                if(popupWindow!=null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                    return;
                }
                popupWindow = PopuRecycle.setPopuThemes(this,v, status,statu, new PopuRecycle.OnClickState() {
                    @Override
                    public void OnItemClick(Object model, PopuRecycle.EnumType enumType) {
                        Base base = (Base) model;
                        if(statu != base) {
                            statu = base;
                            act_there.setText(statu.title);
                            isForce = true;
                            getInitNetwork(false);
                        }
                    }
                });
                break;
            case R.id.act_four:
                if(!isRequestList(sorts)){
                    PromptManager.showToast(R.string.city_sort_hint);
                    return;
                }
                if(popupWindow!=null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                    return;
                }
                popupWindow = PopuRecycle.setPopuThemes(this,v, sorts,sort, new PopuRecycle.OnClickState() {
                    @Override
                    public void OnItemClick(Object model, PopuRecycle.EnumType enumType) {
                        Base base = (Base) model;
                        if(sort != base) {
                            sort = base;
                            act_four.setText(sort.title);
                            isForce = true;
                            getInitNetwork(false);
                        }
                    }
                });
                break;
        }
    }



    /**
     * 获取类型id
     * @return
     */
    private String themeItemId(Base base){
        String id = ApplicationConfig.ALL_TYPE_ID;
        if (base != null){
            id = String.valueOf(base.id);
        }
        return id;
    }

    @Override
    public void initViewHandler() {
        if(recycler == null)return;
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);

        recycler.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL,
                CommonUtil.dip2px(QXApplication.getContext(),1),
                getResources().getColor(R.color.divider)));
        recycler.setLayoutManager(layoutVerManager);
    }

    @Override
    public void initSucessView() {}
}
